/**
 * @format
 * @Author: TC
 * @Date: 2021-09-26 13:43:05
 * @Last Modified by: TC
 * @Last Modified time: 2023-07-27 16:33:18
 */

import { _decorator, approx, director, Node } from "cc";
import { app } from "../App";
import { LoadingWindow } from "../CCComponent/Window/LoadingWindow";
import { SingleBase } from "../Interface/SingleBase";
import { BaseScene } from "../Module/Component/BaseScene";
import { BundleItem } from "../Module/Res/BundleItem";

/**
 * 场景管理
 */
export class SceneManager {
    private sceneName: string = ""; //场景名称
    private bundleName: string = ""; //资源包名称
    public bundleItem: BundleItem = null; //资源包名称

    /**
     * 运行场景
     * @param sceneName 场景名称
     * @param bundleName 包名称(场景不在bundle中时填空)
     */
    public runScene(sceneName: string, bundleName: string = ""): void {
        app.uiMgr.destroyAllWindows();
        this.sceneName = sceneName;
        this.bundleName = bundleName;
        if ("" == this.bundleName) {
            this._preloadScene();
            return;
        }
        app.resMgr.loadBundle(this.bundleName, (bundleItem: BundleItem) => {
            this.bundleItem = bundleItem;
            this._preloadScene();
        });
    }

    /**
     * 预加载场景
     */
    private _preloadScene(): void {
        //显示加载界面
        director.preloadScene(
            this.sceneName,
            (complete, total, item) => {},
            (err, scene) => {
                if (err) app.log.log(err.message);
                else {
                    app.log.log("加载场景成功-" + this.sceneName);
                    this._runNextScene();
                }
            }
        );
    }

    /**
     * 运行下一场景
     */
    private _runNextScene(): void {
        director.loadScene(this.sceneName);
    }

    /**
     * 获取当前画布节点
     */
    public getCurrCanvasNode(): Node {
        return director.getScene().getChildByName("Canvas");
    }
    /**
     * 获取当前场景组件
     */
    public getCurrScene(): BaseScene {
        const sceneComp = director.getScene().getComponentInChildren(BaseScene);
        if (!sceneComp) {
            app.log.error("find sceneComp err");
        }
        return sceneComp;
    }
}
